package com.eshop.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class JdbcUtils {

    private  static DruidDataSource dataSource;

    static {
        try {
            Properties properties = new Properties();
            // 读取jdbc.properties属性配置文件
            InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            // 从流中加载数据
            properties.load(inputStream);
            // 创建 数据库连接池
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection connection = null;

        try {
            connection = dataSource.getConnection();
        } catch (Exception throwable) {
            throwable.printStackTrace();
        }

        return connection;
    }

    public static void close(Connection connection){
        if(connection != null){
            try {
                connection.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
